package com.bdqn.realm;

import com.bdqn.Service.SysRoles.SysRolesService;
import com.bdqn.Service.SysUsers.SysUsersService;
import com.bdqn.entity.SysRoles;
import com.bdqn.entity.SysUsers;
import com.bdqn.mapper.SysRoles.SysRolesMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义realm
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    SysUsersService sysUsersService;
    @Autowired
    SysRolesService sysRolesService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        List<SysRoles> byUserName = sysRolesService.findByUserName(primaryPrincipal);
        List<String> list=new ArrayList<String>();
        for (SysRoles sysRoles : byUserName) {
            list.add(sysRoles.getName());
        }
        //交给shiro授权认证
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            //添加角色信息
        info.addRoles(list);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String LoginId = (String) authenticationToken.getPrincipal();
        Object Password= authenticationToken.getCredentials();
        SysUsers sysUsers=sysUsersService.findByName(LoginId);
        if(sysUsers==null){
            throw new UnknownAccountException();
        }
        return new SimpleAuthenticationInfo(sysUsers.getLoginId(),sysUsers.getPassword(),new Md5Hash(Password),this.getName());
    }
}
